package com.guojiang.guopicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.http.server.filter.HttpFilter;
import com.guojiang.guopicturebackend.config.CosClientConfig;
import com.guojiang.guopicturebackend.exception.BusinessException;
import com.guojiang.guopicturebackend.exception.ErrorCode;
import com.guojiang.guopicturebackend.exception.ThrowUtils;
import com.guojiang.guopicturebackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * （图片）文件处理通用类 
 * @Deprecated 已废弃，改为使用 upload 包的模板方法优化
 */
@Slf4j
@Service
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    /**
     * 引入写好的对象存储通用类
     */
    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     *
     * @param multipartFile    文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 1. 校验图片大小、格式（可以自定义添加其他逻辑）
        validPicture(multipartFile);
        // 2. 图片上传地址（格式化时间 + 随机Id + 文件名）
        // 自己拼接文件名，可以增加安全性
        String uuid = RandomUtil.randomString(16);
        String originalFilename = multipartFile.getOriginalFilename();
        // 拼接文件名称
        String uploadPictureName = String.format("%s_%s.%s",
                DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFilename));
        // 拼接最终的文件上传路径
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadPictureName);
        // 3. 上传图片文件
        // 新建临时文件
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(uploadPath, null);
            // multipartFile 传输到 file
            multipartFile.transferTo(file);
            // 执行
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取图片上传后的图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 计算宽高
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            // 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 删除临时文件
            this.deleteTempFile(file);
        }
    }

    /**
     * 校验图片文件
     *
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "图片文件不能为空");
        // 1. 校验图片大小
        long pictureSize = multipartFile.getSize();
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(pictureSize > 20 * ONE_M, ErrorCode.PARAMS_ERROR, "图片大小不能超过 20MB");
        // 2. 校验文件后缀
        // 获取文件后缀
        String pictureSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 定义允许上传的文件后缀列表
        final List<String> ALLOW_SUFFIX_LIST = Arrays.asList("jpeg", "png", "jpg", "webp", "bmp", "svg");
        ThrowUtils.throwIf(!ALLOW_SUFFIX_LIST.contains(pictureSuffix)
                , ErrorCode.PARAMS_ERROR, "不支持上传该类型的图片");
    }

    /**
     * 清理临时文件
     *
     * @param file
     */
    public void deleteTempFile(File file) {
        if (file != null) {

            boolean deleteResult = file.delete();
            if (!deleteResult) {
                log.error("file delete error, filepath = {}", file.getAbsolutePath());
            }
        }
    }

    /**
     * 通过 url 上传图片
     *
     * @param fileUrl          文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
        // 1. 校验图片URL（可以自定义添加其他逻辑）
        validPictureUrl(fileUrl);
        // 2. 图片上传地址（格式化时间 + 随机Id + 文件名）
        // 自己拼接文件名，可以增加安全性
        String uuid = RandomUtil.randomString(16);
//        String originalFilename = multipartFile.getOriginalFilename();
        String originalFilename = FileUtil.mainName(fileUrl);
        // 拼接文件名称
        String uploadPictureName = String.format("%s_%s.%s",
                DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFilename));
        // 拼接最终的文件上传路径
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadPictureName);
        // 3. 上传图片文件
        // 新建临时文件
        File file = null;
        // 上传文件
        try {
            file = File.createTempFile(uploadPath, null);
            HttpUtil.downloadFile(fileUrl, file);
            // 执行
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 获取图片上传后的图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 计算宽高
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            // 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 删除临时文件
            this.deleteTempFile(file);
        }
    }

    /**
     * 校验图片URL
     *
     * @param fileUrl
     */
    private void validPictureUrl(String fileUrl) {
        // 1. 校验非空
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "图片地址为空");
        // 2. 校验 URL 格式
        // 利用Java自带的URL对象，判断格式是否正常
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片地址格式非法");
        }
        // 3. 校验 URL 协议（是否以 http:// 或 https:// 开头）
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://")
                , ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的图片地址");
        // 4. 发送 HEAD 请求验证文件是否存在
        HttpResponse httpResponse = null;
        try {
            // 非正常返回，无需执行其他判断，也不需要报错
            httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 5. 文件存在，文件类型校验
            String contentType = httpResponse.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/png", "image/jpg"
                        , "image/webp", "image/bmp", "image/svg");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType)
                        , ErrorCode.PARAMS_ERROR, "不支持上传该类型的图片");
            }
            // 6. 文件存在，文件大小校验
            String contentLengthStr = httpResponse.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long ONE_M = 1024 * 1024;
                    ThrowUtils.throwIf(contentLength > 4 * ONE_M, ErrorCode.PARAMS_ERROR, "图片大小不能超过 4MB");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小格式异常");
                }
            }
        } finally {
            // 释放资源
            if (httpResponse != null) {
                httpResponse.close();
            }
        }
    }
}
